const container = document.querySelector('.container'); 
const containerWrapper = document.querySelector('.container-wrapper')
const imgList = container.querySelectorAll('.img img');
const dots = container.querySelectorAll('.dot');
let currentIndex = 0;
let timer = null;

function updatePosition(index) {
 containerWrapper.style.left = -(index * 640) + 'px'; 
}

function changeImg(index) {
 if (index < 0 || index >= imgList.length) {
 return;
}

imgList.forEach((img, i) => {
 img.classList.remove('active');
 dots[i].classList.remove('active');
});

imgList[index].classList.add('active');
dots[index].classList.add('active');

currentIndex = index;
updatePosition(index);
}

function autoPlay() {
timer = setInterval(() => {
let index = currentIndex + 1;
if (index >= imgList.length) {
index = 0;
}
changeImg(index);
}, 2000);
}

function stopPlay() {
clearInterval(timer);
timer = null; 
}

function initCarousel() {
changeImg(currentIndex);

container.addEventListener('mouseover', stopPlay);
container.addEventListener('mouseout', () => {
if (timer === null) {
  autoPlay();
}
});
dots.forEach((dot, index) => {
dot.addEventListener('click', () => {
changeImg(index);
});
});

autoPlay();
}

initCarousel();